// signalr.js

import * as signalR from "@microsoft/signalr";

let token = null;
const storedToken = localStorage.getItem("jst:token");

if (storedToken && storedToken.length > 7) {
    token = storedToken.substring(7);
}

let host = import.meta.env.VITE_WEB_SOCKET;
// console.log("host",host)

const connection = new signalR.HubConnectionBuilder()
  .withUrl(host, {
    accessTokenFactory: () => token,
  }) //http://localhost:5000/chatHub
  .withAutomaticReconnect() // 设置自动重连机制
  .build();

// 失去连接时的处理逻辑
const handleConnectionClosed = (error) => {
  if (error) {
    console.log("SignalR connection closed with an error:");
  } else {
    console.log("SignalR connection closed");
  }

  // 在这里可以添加重新连接的逻辑
  // 例如，调用 startConnection() 方法重新建立连接
  //startConnection();
};

// 配置连接关闭事件处理
connection.onclose((error) => {
  handleConnectionClosed(error);
});

const startConnection = async () => {
  try {
    await connection.start();
    console.log("SignalR connected");
  } catch (err) {
    console.error("Error connecting to SignalR:", err);
    // 在连接失败时也可以处理重新连接的逻辑
    // 例如，定时重新连接
    // setTimeout(startConnection, 3000); // 5秒后尝试重新连接
  }
};

const sendMessage = (user, message) => {
  connection.invoke("SendMessage", user, message);
};

const receiveMessage2 = (callback) => {
  connection.on("ReceiveMessage", (user, message) => {
    callback(`${user}: ${message}`);
  });
};
const receiveMessage = (callback) => {
  connection.on("ReceiveMessage", (message) => {
    callback(`${message}`);
  });
};

const vaildConnectionAlive=()=>{
  return connection.state===signalR.HubConnectionState.Connected
}

export default {
  startConnection,
  sendMessage,
  receiveMessage,
  vaildConnectionAlive
};
